from flask import Blueprint, render_template, flash, redirect, url_for, request, jsonify, session, g
from flask_login import current_user, login_required

from apps.forms.album_episode_info_form import *
from rules.album_episode_info_rule import *
from rules.album_info_rule import search_album_info

album_episode = Blueprint('album_episode_info', __name__, url_prefix='/album/<album_id>/album_episode')
ACTIVE = 'album'
ACTIVE_ITEM = 'album_episode_info'
SEARCH_PAGE = 'album_episode_info_page'


@album_episode.url_value_preprocessor
def pull_user_url_slug(endpoint, values):
    g.album_id = values.pop('album_id')
    g.album_info = search_album_info(g.album_id)


@album_episode.route('/page', methods=['POST', 'GET'])
@login_required
def page():
    form = QueryAlbumEpisodeInfoForm(csrf_enabled=False)
    form.album_id.data = g.album_id

    last_search = session.get('last_search')
    page_index = 1
    title = ''

    if request.method == 'GET':
        if last_search and last_search.get('search_page', '') == SEARCH_PAGE:
            page_index = last_search.get('page_index', 1)
            if last_search.get('search_data'):
                title = last_search.get('search_data').get('title', '')

        page_index = request.args.get('page', page_index, type=int)

        title = request.args.get('title', title)
        form.title.data = title

    else:
        page_index = 1
        if form.title.data:
            title = form.title.data

    search_data = dict(album_info_id=g.album_id, title=title)
    last_search = dict(search_page=SEARCH_PAGE, page_index=page_index, search_data=search_data)
    session['last_search'] = last_search

    pagination = search_album_episode_info_with_page(page_index, search_data)

    return render_template('album_episode_info/page.html', pagination=pagination, form=form, active=ACTIVE,
                           active_item=ACTIVE_ITEM, album_info=g.album_info)


@album_episode.route('/create', methods=['POST', 'GET'])
@login_required
def create():
    form = CreateAlbumEpisodeInfoForm()
    form.album_id.data = g.album_id
    if form.validate_on_submit():
        try:
            create_album_episode_info(form, current_user)
            flash('新增成功', 'page_success')
            return redirect(url_for('album_episode_info.page', album_id=g.album_id))
        except Exception as e:
            g.exception_occurred = e
            flash(str(e), 'page_error')

    return render_template('album_episode_info/create.html', form=form, active=ACTIVE,
                           active_item=ACTIVE_ITEM, album_info=g.album_info)


@album_episode.route('/edit/<int:id>', methods=['POST', 'GET'])
@login_required
def edit(id):
    album_episode_dict = search_album_episode_info_by_album_id(g.album_id, id)
    if not album_episode_dict:
        return redirect(url_for('album_episode_info.page'))

    if request.method == 'GET':
        form = UpdateAlbumEpisodeInfoForm(album_episode_dict)
    else:
        form = UpdateAlbumEpisodeInfoForm()

    form.album_id.data = g.album_id

    if form.validate_on_submit():
        try:
            describe_album_episode_info(id, form, current_user)
            flash('修改成功', 'page_success')
            return redirect(url_for('album_episode_info.page', album_id=g.album_id))
        except Exception as e:
            g.exception_occurred = e
            flash(str(e), 'page_error')

    return render_template('album_episode_info/edit.html', album_info=g.album_info, form=form, active_item=ACTIVE_ITEM)
